<template>
  <div class="container-fluid w-75 mx-auto pt-5">
    <todo-header
      @add="add"
      @changeAll="changeAll"
      :checkedAll="checkedAll"
    ></todo-header>
    <todo-main
      :filterList="filterList"
      @del="del"
      @oneChecked="oneChecked"
    ></todo-main>
    <todo-footer
      :btnText="btnText"
      :iNum="iNum"
      :dNum="dNum"
      :activeText="activeText"
      @changeActive="changeActive"
      @del="del"
    ></todo-footer>
  </div>
</template>

<script>
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
import TodoFooter from "./components/TodoFooter.vue";

export default {
  data() {
    return {
      btnText: ["全部", "未完成", "已完成"],
      activeText: "全部",
      text: "",
      list: localStorage.getItem("list")
        ? JSON.parse(localStorage.getItem("list"))
        : [],
    };
  },

  methods: {
    changeActive(value) {
      this.activeText = value;
    },
    changeAll(value) {
      this.list.forEach((v) => (v.done = value));
    },
    oneChecked(id) {
      const index = this.list.findIndex((v) => v.id === id);
      this.list[index].done = !this.list[index].done;
    },
    add(value) {
      this.list.push({
        id: this.list.length > 0 ? this.list[this.list.length - 1].id + 1 : 1,
        html: value,
        done: false,
      });
    },
    del(id = "") {
      const index = this.list.findIndex((i) => i.id === id);
      if (index === -1) {
        this.list = this.list.filter((v) => v.done === false);
      } else {
        this.list.splice(index, 1);
      }
    },
  },

  watch: {
    list: {
      deep: true,
      handler(nv) {
        localStorage.setItem("list", JSON.stringify(nv));
      },
    },
  },

  computed: {
    filterList() {
      if (this.activeText === "全部") {
        return this.list;
      } else if (this.activeText === "未完成") {
        return this.list.filter((v) => v.done === false);
      } else if (this.activeText === "已完成") {
        return this.list.filter((v) => v.done === true);
      } else {
        return [];
      }
    },
    checkedAll: {
      get() {
        return (
          this.list.length &&
          this.list.filter((v) => v.done === true).length === this.list.length
        );
      },
    },
    iNum() {
      return this.list.filter((v) => !v.done).length;
    },
    dNum() {
      return this.list.length-this.list.filter((v) => !v.done).length;
    },

  },

  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
};
</script>

<style>
</style>